package com.lonely.fx.image;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @date: 2022-07-26 22:32
 * @author: ztkj-hzb
 * @description: 将像素写入到图片中
 **/
public class WritableImageSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {


        HBox hBox = new HBox();

        //TODO 创建一个空图片，用于写入像素
        //构造方法1--创建一个固定宽高的空图片
        WritableImage writableImage = new WritableImage(200, 200);

        //写入像素--直接单独设置固定位置的像素
        PixelWriter pixelWriter = writableImage.getPixelWriter();
        for (int i = 0; i < 200; i++) {
            for (int j = 0; j < 200; j++) {
                pixelWriter.setColor(j, i, Color.PINK);
            }
        }


        //构造方法2--创建一个携带数据的图片
        Image image = new Image("icons/welcome.jpg");
        WritableImage writableImage2 = new WritableImage(image.getPixelReader(), (int) image.getWidth(), (int) image.getHeight());

        //写入像素--使用另一个图片的数据来覆盖当前图片
        PixelWriter pixelWriter2 = writableImage2.getPixelWriter();
        Image tempImage = new Image("icons/shuidi.jpg");
        pixelWriter2.setPixels(0, 0, (int) (image.getWidth() / 2), (int) (image.getHeight()), tempImage.getPixelReader(), 0, 0);



        //TODO 如何将内存的图片写入到本地
        BufferedImage bufferedImage = SwingFXUtils.fromFXImage(writableImage2, null);
        ImageIO.write(bufferedImage,"png",new File("D:/a.png"));


        ImageView imageView = new ImageView(writableImage2);

        //截图工具
        WritableImage snapshot = imageView.snapshot(null, null);
        BufferedImage bufferedImage2 = SwingFXUtils.fromFXImage(snapshot, null);
        ImageIO.write(bufferedImage2,"png",new File("D:/b.png"));


        hBox.getChildren().addAll(imageView);
        primaryStage.setScene(new Scene(hBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();
    }
}
